from rest_framework.permissions import BasePermission, SAFE_METHODS


class MainPermissions(BasePermission):
    """
    权限: 必须具有项目五的权限
    对象权限: 审核通过/已提交的数据不可操作; 非自己对象不可操作只可查看
    """

    def has_permission(self, request, view):
        user = request.user
        all_perm = user.get_all_permissions()
        own_perm = [perm for perm in all_perm if perm.startswith('prj005')]

        if not own_perm:
            return False

        return True

    def has_object_permission(self, request, view, obj):

        if hasattr(obj, 'info'):
            obj = obj.info

        if request.method in SAFE_METHODS:
            return True
        else:
            if hasattr(obj, 'check_status'):
                if obj.check_status in ('审核通过', '已提交'):
                    return False

            return obj.owner == request.user


class MobileClientPermission(BasePermission):
    ''' for mobile login person '''

    def has_permission(self, request, view):
        if request.method not in SAFE_METHODS:
            if request.user.has_perm('prj005.prj005_patient'):
                return True
            else:
                return False
